<?php if(!defined('BASEPATH')) exit('Woa...Not find system folder');

/*
 * User Controller Admin
 * Package: Admin controller
 * Author: Nguyen Duc Hung
 * Email: tinapc@gmail.com
 * Webiste: http://tina-web.net
 * Date: 15/07/2012
 */

class User extends admin_controller {

    function __construct() {

        parent::__construct();

        $this->load->model('user/user_group_model', 'user_group');
        $this->load->model('user/user_model', 'user');
    }
	
	
    public function index() {

        //$this->check_login();
        $this->permission_view('user');		

        // Delete from list
        $del = $this->input->post('selected');
        $act = $this->input->post('act');

        if($act == 'act_del')
        {
            if($del)
            {
                if(gettype($del) == 'array' && count($del) > 0)
                {
                    // Do something
                }
            } else {
                $this->session->set_flashdata('warning', $this->lang->line('warning_request'));
                redirect('/admin/user');
            }
        } // End action delete from list

        $sql = $this->db->where('user_name !=', 'admin')
                        ->order_by('user_id', 'desc')
                        ->get('user_user');

        $users = '';

        if($sql->num_rows() > 0)
        {
            foreach($sql->result() as $user)
            {
                $users[] = array(
                    'user_id'		=> $user->user_id,
                    'user_name'		=> $user->user_name,
                    'user_email'	=> $user->user_email,
                    'user_full'		=> $user->user_fullname,
                    'user_active'	=> $user->user_active,
                    'user_group'	=> $user->user_group_id,
                    'url_del'		=> URL_ADMIN .'user/delete/' . $user->user_id,
                    'url_edit'		=> URL_ADMIN .'user/add/' . $user->user_id
                );
            }
        } 
        //$users = $sql->result();
        $groups = $this->db->get('user_group');
        $groups = $groups->result();		

        $txt = array(
            'a_add' => URL_ADMIN.'user/add',
            'a_del' => URL_ADMIN.'user/delete/',
            'a_del_group' => URL_ADMIN.'user/delete_group/',
            'link_load_group' => URL_ADMIN. 'user/loadListGroup',
            'a_edit' => URL_ADMIN.'user/edit/',
            'a_change_status' => URL_ADMIN .'user/change_status',
            'a_change_group' => URL_ADMIN .'user/change_group'
        );

        $this->template->title(t_lang('manager_user'), $this->config->item('site_cms'))
                       ->set(array('txt' => $txt, 'groups' => $groups))
                       ->build('admin/user/user_index', array('users' => $users));

    }
    
    public function delete_group()
    {
        //$this->permission_modifi('user_group');
		
        $id = $this->input->post('id');
        if($this->permission_modifi('user_group'))
        {
            if($this->user_group->delete($id)) {
                $mess = array('message' => t_lang('delete_success'));
            } else {
                $mess = array('message' => t_lang('delete_faild'));
                
            }
        } else {
             $mess = array('message' => t_lang('denied_access'));	
        }
        
        echo json_encode($mess);
    }
    
        
    function loadListGroup()
    {
        $groups = $this->db->get('user_group');
        $data['groups'] = $groups->result();
        $data['a_edit'] = URL_ADMIN.'user/edit_group_form/';
        $data['a_add_group'] = URL_ADMIN.'user/add_group';
        
        $this->load->view('admin/user/loadListGroup', $data);
    }
    
    
    public function add_group()
    {
        
        // Lay tat ca cac file trong controllers admin
        $permissions = array();

        $files = glob('application/controllers/admin/*.php');
        $file_igore = array('permission', 'home', 'language', 'login', 'logout');
        if(count($files)) 
        {
            foreach($files as $file) 
            {
                $permis = basename($file,'.php');	

                if(!in_array($permis, $file_igore)) 
                {
                    $permissions[] = $permis;
                }
            }
        }

        $_id = (int)$this->uri->segment(4);
        if($_id) 
        {
            $result = $this->user_group->read($_id);

            $group_id = $result->user_group_id;
            $group_name = $result->user_group_name;
            $permission_view = unserialize($result->permission_view);
            $permission_edit_delete = unserialize($result->permission_edit_del);			
        }
        
        $data['permissions'] = $permissions;
        $data['a_action_add_group'] = URL_ADMIN.'user/add_group_action';
        $this->load->view('admin/user/add_group', $data);
    }
    
    function add_group_action()
    {
        $data['name']   = $this->input->post('groupName');
        
        $perView = $this->input->post('perView');
        $perView = explode(',', $perView);
        $data['permis_view']= serialize($perView);
        
        $perEdit = $this->input->post('perEdit');
        $perEdit = explode(',', $perEdit);
        $data['permis_edit_delete'] = serialize($perEdit);
        
		if($this->permission_modifi('user'))
		{
			if($this->user_group->create($data)) 
			{
				$mess = array('message' => t_lang('add_success'));
			} else {
				$mess = array('message' => t_lang('add_faild'));
			}
		} else {
			$mess = array('message' => t_lang('denied_access'));
		}
        
        echo json_encode($mess);
        
    }
	
	public function edit_group_form()
	{
		// Get data from $_POST
		$id = $this->uri->segment(4);
		
		// Lay tat ca cac file trong controllers admin
        $permissions = array();

        $files = glob('application/controllers/admin/*.php');
        $file_igore = array('permission', 'home', 'language', 'login', 'logout');
        if(count($files)) 
        {
            foreach($files as $file) 
            {
                $permis = basename($file,'.php');	

                if(!in_array($permis, $file_igore)) 
                {
                    $permissions[] = $permis;
                }
            }
        }
		
		if($id) 
        {
            $result = $this->user_group->read($id);

            $group_id = $result->user_group_id;
            $group_name = $result->user_group_name;
            $permission_view = unserialize($result->permission_view);
            $permission_edit_delete = unserialize($result->permission_edit_del);			
        }
        
        $data['permissions'] = $permissions;
		$data['group_name'] = $group_name;
		$data['per_views_old'] = $permission_view;
		$data['per_edits_old'] = $permission_edit_delete;
		$data['oldId'] = $id;
        $data['a_action_edit_group'] = URL_ADMIN.'user/action_edit_group';
		
        $this->load->view('admin/user/form_edit_group', $data);
		
			
	}
	
	public function action_edit_group()
	{
		$id = $this->input->post('id');
		
		$data['name']   = $this->input->post('groupName');
        
        $perView = $this->input->post('perView');
        $perView = explode(',', $perView);
        $data['permis_view']= serialize($perView);
        
        $perEdit = $this->input->post('perEdit');
        $perEdit = explode(',', $perEdit);
        $data['permis_edit_delete'] = serialize($perEdit);
		
		if($this->permission_modifi('user'))
		{
			if($this->user_group->update($id, $data)) 
			{
				$mess = array('message' => t_lang('update_success'));
			} else {
				$mess = array('message' => t_lang('update_faild'));
			}
		} else {
			$mess = array('message' => t_lang('denied_access'));
		}
        
        echo json_encode($mess);
	}
    
    
    
    /*--------------------
    ## Function profile ##
    --------------------*/
    function profile() {

        $id = $this->session->userdata('user_id');

        $this->form_validation->set_rules('fullname', 'Fullname', 'required');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');

        $data['render_path'] = array('Admin' => $this->index_url.'admin', 'User' => $this->index_url.'admin/user', 'Thay đổi thông tin' => '');
        $data['heading_top'] = 'Thay đổi thông tin&nbsp;<b>'. $this->session->userdata('username').'</b>';
        $data['action'] = $this->index_url.'admin/user/profile';

        $data['user_fullname'] = $this->input->post('fullname');
        $data['user_email'] = $this->input->post('email');

        if($this->form_validation->run() == TRUE) {

            if($this->user->update($id,$data)) {
                    $this->session->set_flashdata('message', 'Cập nhật thông tin thành công');
                    redirect('admin/user/profile');
            } else {
                    $this->session->set_flashdata('message', 'Có lỗi trong quá trình cập nhật');
                    redirect('admin/user/profile');
            }

        }

        $data['user'] = $this->user->read($id);

        $this->render($this->load->view('admin/account/profile_form', $data, TRUE));

    }
	
	
	/*--------------------
	## Function change_pass ##
	--------------------*/
	function change_password() 
	{
            $data = array();

            $txt['act_form'] = URL_ADMIN.'user/change_password';

            $id = $this->session->userdata('user_id');

            $this->form_validation->set_rules('oldpass', 'Mật khẩu cũ', 'trim|required');
            $this->form_validation->set_rules('newpass', 'Mật khẩu mới', 'trim|required|matches[comfirm_pass]');
            $this->form_validation->set_rules('comfirm_pass', 'Mật khẩu xác nhận', 'trim|required');

            $oldpass = md5($this->input->post('oldpass'));
            $newpass = md5($this->input->post('newpass'));

            if($this->form_validation->run() == TRUE) {
                
				$sql = $this->db->update('user', array('password' => $newpass), array('id' => $id));
				
				if(!$sql) {
                    $this->session->set_flashdata('info', 'Mật khẩu cũ không đúng');
                    redirect('admin/user/change_password');
                } else {
                    $this->message('info', 'Update successfuly');
                    
					if($this->session->userdata('logined') == TRUE) {

						$data = array (
							'user_id' 		=> '',
							'username' 		=> '',
							'fullname' 		=> '',
							'logined'		=> FALSE
						);

						$this->session->unset_userdata($data);

						$this->session->set_flashdata('error', t_lang('logout_success'));

						redirect('admin/login', 'refresh');

					}
					
					//redirect('admin/home');
                }
            }

		$this->template->title('Thay mật khẩu')
		               ->set('link_action', URL_ADMIN .'user/change_password')
					   ->build('admin/account/change_pass_form');
	
	}
	
	
    public function delete() {

        $user_id = (int)$this->input->post('id');

        if($this->permission_modifi('user'))
        {
            if($this->user->delete($user_id)) {
             	$mess = array('message' => t_lang('delete_success'));
            } else {
				$mess = array('message' => t_lang('delete_faild'));
            }
        } else {
             $mess = array('message' => t_lang('denied_access'));	
        }
		
		echo json_encode($mess);

    }
	
	/*--------------------
	## Function create ##
	--------------------*/
	
	public function add() 
	{	
		if($this->permission_modifi('user'))
		{
			$data = array();
		
			// Config form_valid
			$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
			$this->form_validation->set_rules('password', 'Password', 'trim|required|matches[confirm_password]|xss_clean');
			$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required');
			$this->form_validation->set_rules('user_email', 'Email', 'required|valid_email');
			//$this->form_validation->set_rules('group', 'Select group', 'required');
			$this->form_validation->set_rules('fullname', 'Full name', '');
			$this->form_validation->set_rules('active', 'Active', '');
			
			// Get data from $_POST
			$data['user_name'] 			= $this->input->post('username');
			$data['user_password'] 		= md5($this->input->post('password'));
			$data['user_email'] 		= $this->input->post('user_email');
			$data['user_fullname'] 		= $this->input->post('user_fullname');
			$data['user_active'] 		= ($this->input->post('active') == 'on') ? 1 : 0;
			$data['user_group'] 		= (int) $this->input->post('user_group');
		
		
			if($this->form_validation->run() == TRUE) {
				
				
					if(!$this->user->check_username($data['user_name']) && !$this->user->check_email($data['user_email'])) {
						$this->message('error', $this->lang->line('txt_user_email_exist'));
						redirect(URL_ADMIN . 'user/add/');
					} else if (!$this->user->check_username($data['user_name'])) {
						$this->message('error', $this->lang->line('txt_user_exist'));
						redirect(URL_ADMIN . 'user/add/');
					} else if(!$this->user->check_email($data['user_email'])) {
						$this->message('error', $this->lang->line('txt_email_exist'));
						redirect(URL_ADMIN . 'user/add/');
					} else {
					
						if($this->user->create($data)) {
							$this->message('info', t_lang('add_success'));
							redirect(URL_ADMIN . 'user/');
						} else {
							$this->message('error', t_lang('add_fail'));
							redirect(URL_ADMIN . 'user/add/');
						}
					}
				
			}
		
		
			$groups = $this->user_group->get()->result();
			$txt = array(
				'url_action' => URL_ADMIN.'user/add',
				'url_cancel' => URL_ADMIN.'user'
			);
		} else {
			$this->message('warning', t_lang('denied_access'));
			redirect(URL_ADMIN . 'user');
		}
		
		$this->template->title(t_lang('create_new'), $this->config->item('site_cms'))
		               ->set(array('txt'=> $txt, 'groups' => $groups))
					   ->build('admin/user/user_create_form');
		
	}
	
	
	public function edit()
	{
		if($this->permission_modifi('user'))
		{
			$data = array();
			
			// Config form_valid
			$this->form_validation->set_rules('password', 'Password', 'trim|required|matches[confirm_password]|xss_clean');
			$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required');
			$this->form_validation->set_rules('user_email', 'Email', 'required|valid_email');
			//$this->form_validation->set_rules('group', 'Select group', 'required');
			$this->form_validation->set_rules('fullname', 'Full name', '');
			$this->form_validation->set_rules('active', 'Active', '');
			
			// Get data from $_POST
			$data['user_name'] 			= $this->input->post('username');
			$data['user_password'] 		= md5($this->input->post('password'));
			$data['user_email'] 		= $this->input->post('user_email');
			$data['user_fullname'] 		= $this->input->post('user_fullname');
			$data['user_active'] 		= ($this->input->post('active') == 'on') ? 1 : 0;
			$data['user_group'] 		= (int) $this->input->post('user_group');
			$oldId = $this->input->post('oldId');
			
			if($this->form_validation->run() == TRUE) {							
						if($this->user->update($oldId,$data)) {
							$this->message('info', t_lang('update_success'));
							redirect(URL_ADMIN . 'user/');
						} else {
							$this->message('error', t_lang('update_fail'));
							redirect(URL_ADMIN . 'user/add/');
						}
			}
		
			$groups = $this->user_group->get()->result();
			$userInfo = $this->user->read($this->uri->segment(4));
			$txt = array(
				'url_action' => URL_ADMIN.'user/edit/' .$this->uri->segment(4),
				'url_cancel' => URL_ADMIN.'user'
			);
		} else {
			$this->message('warning', t_lang('denied_access'));
			redirect(URL_ADMIN . 'user');
		}	
		
		$this->template->title(t_lang('edit_item'), $this->config->item('site_cms'))
		               ->set(array('txt'=> $txt, 'groups' => $groups, 'userInfo' => $userInfo))
					   ->build('admin/user/user_edit_form');	
	}
	
	/*
	* Change stauts of user Function	
	*/
    
    function change_status()
    {
        if($this->permission_modifi('user'))
		{
			$status = $this->input->post('id');
			$langID = $this->input->post('langId');
			
			if($this->db->update('user_user', array('user_active' => $status), array('user_id' => $langID)))
			{
				$mess = array('message' => t_lang('update_success'));
			} else {
				$mess = array('message' => t_lang('update_faild'));
			}
		} else {
			$mess = array('message' => t_lang('denied_access'));
		}
        
        echo json_encode($mess);
    }
    
    function change_group()
    {
        if($this->permission_modifi('user'))
		{
		
			$status = $this->input->post('groupId');
			$langID = $this->input->post('userId');
			
			if($this->db->update('user_user', array('user_group_id' => $status), array('user_id' => $langID)))
			{
				$mess = array('message' => t_lang('update_success'));
			} else {
				$mess = array('message' => t_lang('update_faild'));
			}
		} else {
			
			$mess = array('message' => t_lang('denied_access'));
		}
        
        echo json_encode($mess);
    }
	
}
/* End file user.php */
/* Local application/controllers/admin/user.php */